const mysql = require('mysql2/promise');

async function updateBasicItemsShopStatus () {
  const connection = await mysql.createConnection({
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    timezone: '+08:00'
  });

  try {
    console.log('🔧 更新基础物品商店上架状态...\n');

    // 宝物商店物品列表
    const treasureShopItems = [
      { name: "将军令", price: 30, pic: "jjl.png" },
      { name: "大将军令", price: 200, pic: "djjl.png" },
      { name: "护身符", price: 298, pic: "hsf.png" },
      { name: "青铜钥匙", price: 20, pic: "qtys.png" },
      { name: "白银钥匙", price: 50, pic: "byys.png" },
      { name: "黄金钥匙", price: 100, pic: "hjys.png" },
      { name: "体力丹", price: 60, pic: "tld.png" },
      { name: "易名神符", price: 6666, pic: "ymsf.png" },
      { name: "原木钥匙", price: 50, pic: "ymys.png" },
      { name: "精钢钥匙", price: 100, pic: "jgys.png" },
      { name: "珍奇钥匙", price: 200, pic: "zqys.png" },
      { name: "兵符", price: 90, pic: "bf.png" },
      { name: "手里剑", price: 500, pic: "slj.png" },
      { name: "签到令牌", price: 100, pic: "qdlp.png" },
      { name: "壕客令牌", price: 9999, pic: "" },
      { name: "超级壕客令牌", price: 19999, pic: "" }
    ];

    // 经验商店物品列表
    const expShopItems = [
      { name: "副将经验书", price: 30, pic: "fjjys.png" },
      { name: "初级副将心法", price: 40, pic: "cjfjxf.png" },
      { name: "高级副将心法", price: 60, pic: "gjfjxf.png" },
      { name: "特级副将心法", price: 80, pic: "tjfjxf.png" },
      { name: "密宗副将心法", price: 100, pic: "mzfjxf.png" },
      { name: "一级技能书", price: 20, pic: "1jjns.png" },
      { name: "二级技能书", price: 40, pic: "2jjns.png" },
      { name: "三级技能书", price: 60, pic: "3jjns.png" },
      { name: "四级技能书", price: 80, pic: "4jjns.png" },
      { name: "五级技能书", price: 100, pic: "5jjns.png" }
    ];

    console.log('📝 步骤1: 重置所有物品的商店状态...');

    // 首先将所有物品的商店状态重置为0
    await connection.execute(`
      UPDATE basic_items 
      SET is_treasure_shop = 0, is_exp_shop = 0, updatedAt = CURRENT_TIMESTAMP
    `);
    console.log('✅ 已重置所有物品的商店状态');

    console.log('\n📝 步骤2: 设置宝物商店物品...');

    let treasureUpdated = 0;
    for (const item of treasureShopItems) {
      try {
        const [result] = await connection.execute(`
          UPDATE basic_items 
          SET is_treasure_shop = 1, is_exp_shop = 0, 
              silver_price = ?, pic = ?, updatedAt = CURRENT_TIMESTAMP
          WHERE name = ?
        `, [item.price, item.pic, item.name]);

        if (result.affectedRows > 0) {
          console.log(`  ✅ 设置宝物商店: ${item.name} - ${item.price}两`);
          treasureUpdated++;
        } else {
          console.log(`  ⚠️ 未找到物品: ${item.name}`);
        }
      } catch (error) {
        console.log(`  ❌ 更新失败: ${item.name} - ${error.message}`);
      }
    }

    console.log('\n📝 步骤3: 设置经验商店物品...');

    let expUpdated = 0;
    for (const item of expShopItems) {
      try {
        const [result] = await connection.execute(`
          UPDATE basic_items 
          SET is_treasure_shop = 0, is_exp_shop = 1, 
              silver_price = ?, pic = ?, updatedAt = CURRENT_TIMESTAMP
          WHERE name = ?
        `, [item.price, item.pic, item.name]);

        if (result.affectedRows > 0) {
          console.log(`  ✅ 设置经验商店: ${item.name} - ${item.price}两`);
          expUpdated++;
        } else {
          console.log(`  ⚠️ 未找到物品: ${item.name}`);
        }
      } catch (error) {
        console.log(`  ❌ 更新失败: ${item.name} - ${error.message}`);
      }
    }

    console.log('\n🔍 步骤4: 验证更新结果...');

    // 验证更新结果
    const [stats] = await connection.execute(`
      SELECT 
        COUNT(*) as total_items,
        COUNT(CASE WHEN is_treasure_shop = 1 THEN 1 END) as treasure_shop_items,
        COUNT(CASE WHEN is_exp_shop = 1 THEN 1 END) as exp_shop_items,
        COUNT(CASE WHEN is_treasure_shop = 0 AND is_exp_shop = 0 THEN 1 END) as no_shop_items
      FROM basic_items
    `);

    console.log('📊 更新后统计:');
    console.log(`  总物品数: ${stats[0].total_items}`);
    console.log(`  宝物商店物品: ${stats[0].treasure_shop_items}`);
    console.log(`  经验商店物品: ${stats[0].exp_shop_items}`);
    console.log(`  未上架物品: ${stats[0].no_shop_items}`);

    // 显示宝物商店物品
    console.log('\n🏪 宝物商店物品列表:');
    const [treasureItems] = await connection.execute(`
      SELECT name, silver_price, pic
      FROM basic_items
      WHERE is_treasure_shop = 1
      ORDER BY silver_price DESC
    `);

    treasureItems.forEach((item, index) => {
      console.log(`  ${index + 1}. ${item.name} - ${item.silver_price}两 - ${item.pic}`);
    });

    // 显示经验商店物品
    console.log('\n📚 经验商店物品列表:');
    const [expItems] = await connection.execute(`
      SELECT name, silver_price, pic
      FROM basic_items
      WHERE is_exp_shop = 1
      ORDER BY silver_price DESC
    `);

    expItems.forEach((item, index) => {
      console.log(`  ${index + 1}. ${item.name} - ${item.silver_price}两 - ${item.pic}`);
    });

    console.log(`\n📊 更新统计:`);
    console.log(`  宝物商店更新: ${treasureUpdated} 个物品`);
    console.log(`  经验商店更新: ${expUpdated} 个物品`);

    console.log('\n🎉 基础物品商店状态更新完成！');

  } catch (error) {
    console.error('❌ 更新失败:', error.message);
    if (error.code) {
      console.error('错误代码:', error.code);
    }
  } finally {
    await connection.end();
    console.log('\n🔌 数据库连接已关闭');
  }
}

// 运行脚本
if (require.main === module) {
  updateBasicItemsShopStatus().catch(console.error);
}

module.exports = { updateBasicItemsShopStatus };
